package com.partner.boot.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.partner.boot.common.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
@ApiOperation(value = "文件管理")
@Slf4j
public class FileController {

    private static final String FILES_DIR = "/files/";

    @Value("${server.port:9090}")
    private String port; // 端口号

    @Value("${file.upload.path:}")
    private String uploadPath; // 上传路径

    @Value("${file.download.ip:}")
    private String downloadIp; // 下载地址ip


    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传接口")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename(); // 文件完整名称
        String fileName = FileUtil.mainName(originalFilename); // 文件主名称
        String extName = FileUtil.extName(originalFilename);  // 文件后缀名
        String uniFileFlag = IdUtil.fastSimpleUUID(); // 随机生成文件名
        String fileFullName = uniFileFlag + StrUtil.DOT + extName;
        // 封装完整的文件路径获取方法 完整的上传路径：E:\个人项目\2022年\partner交友项目\files\hjsadfjahskdfhkasdhf.jpg
        String fileUploadPath = getFileUploadPath(fileFullName);
        long size = file.getSize(); // 文件大小 单位 byte 一般存储kb 转换：size / 1024 -》 kb
        String name = file.getName(); // 上传的文件名称
        try {
            File uploadFile = new File(fileUploadPath);
            File parentFile = uploadFile.getParentFile();
            if (!parentFile.exists()) { // 如果父级目录不存在，就是files目录不存在，就创建files目录
                parentFile.mkdirs();
            }
            file.transferTo(uploadFile);
        }catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败");
        }
        String uploadPath = "http://" + downloadIp + ":" + port + "/file/download/" + fileFullName; // 文件上传后的访问网址
        return Result.success(uploadPath);
    }

    @ApiOperation("文件下载接口")
    @GetMapping("/download/{fileFullName}")
    public void downloadFile(@PathVariable String fileFullName,
                             HttpServletResponse response) throws IOException {
//        List<String> tokenList = StpUtil.getTokenValueListByLoginId(loginId); // 根据用户唯一标识，获取token集合
//        if (CollUtil.isEmpty(tokenList) || !tokenList.contains(token)) { // 如果当前访问的token，在token集合中不存在直接return
//            return;
//        }

        String extName = FileUtil.extName(fileFullName);
        String fileUploadPath = getFileUploadPath(fileFullName);
        byte[] bytes = FileUtil.readBytes(fileUploadPath);
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileFullName, "UTF-8"));  // 预览
        ArrayList<String> attachmentFileExtNames = CollUtil.newArrayList("docx", "doc", "xlsx", "xls", "mp4", "mp3");
        if (attachmentFileExtNames.contains(extName)) {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileFullName, "UTF-8"));  // 附件下载
        }
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }


    public String getFileUploadPath(String fileFullName) {
        if (StrUtil.isBlank(uploadPath)) {
            uploadPath = System.getProperty("user.dir");
        }
        return uploadPath + FILES_DIR + fileFullName;
    }
}
